package com.xci.core.helper;

import cn.hutool.crypto.SecureUtil;
import com.xci.core.base.RestMessage;
import com.xci.core.internal.Sys;

import java.util.regex.Pattern;

public class SecurityHelper {
    /**
     * 密码强度监测正则表达式
     */
    private static Pattern PASSWORD_STRONG_PATTERN;

    /**
     * 验证用户密码强度
     *
     * @param password 密码
     * @return 密码符合强度要求返回true
     */
    public static RestMessage validPwdStrong(String password) {
        if (PASSWORD_STRONG_PATTERN == null) {
            String regex = Sys.setting().getApp().getSysUserPasswordStrongPattern();
            PASSWORD_STRONG_PATTERN = Pattern.compile(regex);
        }
        if (PASSWORD_STRONG_PATTERN.matcher(password).matches()) {
            return RestMessage.success();
        }
        return RestMessage.fail(Sys.setting().getApp().getSysUserPasswordStrongErrorMsg());
    }

    /**
     * 加密用户密码
     *
     * @param account  账号
     * @param password 密码
     * @param salt     密码盐
     * @return 返回加密后的密文
     */
    public static String encryptPassword(String account, String password, String salt) {
        String accountMd5 = SecureUtil.md5(account);
        String passwordMd5 = SecureUtil.md5(password);
        String secretKeyMd5 = SecureUtil.md5(salt);
        return SecureUtil.md5("@" + secretKeyMd5 + "#" + passwordMd5 + "$" + accountMd5 + "%" + secretKeyMd5);
    }

    /**
     * 生成用户密码秘钥
     */
    public static String createSalt() {
        String sj1 = SecureUtil.md5(Helper.guid());
        String sj2 = SecureUtil.md5(Helper.guid());
        return SecureUtil.md5(sj1 + sj2);
    }
}
